package com.engine.cese.duss.tianyancha.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.general.BaseBean;

import java.io.IOException;

/**
 * @Title: ecology-9-demo
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2020-11-17
 * @Description: ${description}
 * @ModifyLog:
 **/

public class HttpClientUtil {
    public static JSONObject sendGetHttpRequest(String url,String token,String URLCode ) {
        BaseBean baseBean = new BaseBean();
        // get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet(url);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(6000).setConnectTimeout(6000).build();
        request.setConfig(requestConfig);
        request.setHeader("Authorization",token);//token值
        try {
            CloseableHttpResponse response = client.execute(request);
            //请求发送成功，并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, URLCode);
                //把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(strResult);
            } else {
                baseBean.writeLog("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            baseBean.writeLog("get请求提交失败:"+e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }
}
